package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("userinfo")
    @ResponseBody
    public String userinfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @PostMapping("/dologin")
    public String doLogin(String username, String password, String url, HttpServletResponse response){
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(token,username);
        //把token存入当前浏览器的cookie当中
        Cookie token_cookie = new Cookie("token_cookie", token);
        response.addCookie(token_cookie);
        return "redirect:"+url+"?token="+token;
    }
    @GetMapping("/login")
    public String login(@RequestParam("redirect_url") String redirectUrl, @CookieValue(value = "token_cookie",required = false) String token, Model model){
        if(!StringUtils.isEmpty(token)){
            //说明已经登录
            return "redirect:"+redirectUrl+"?token="+token;
        }
        model.addAttribute("url",redirectUrl);
        return "login";
    }
}
